import axios from 'axios';
import { checkStatus, handleError } from './checkStatus';

export default function axiosRequest(url, options) {
  const defaultOptions = {
    timeout: 4000,
    dataType: 'json',
    responseType: 'json',
    withCredentials: true,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
    },
  };
  const newOptions = { ...defaultOptions, ...options };

  newOptions.url = url;
  if ('method' in newOptions) {
    newOptions.method = newOptions.method.toUpperCase();
  } else {
    newOptions.method = 'GET';
  }

  if (newOptions.method !== 'GET') {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.data = JSON.stringify(newOptions.body);
    } else {
      newOptions.data = newOptions.body;
    }
  } else {
    newOptions.params = newOptions.body;
  }

  return axios(newOptions)
    .then(checkStatus)
    .then((response) => {
      return response.data;
    })
    .catch(handleError);
}
